from PyQt4.QtCore import *
from PyQt4.QtGui import *

from qgis.core import *
from qgis.gui import *

import time

class cfAction(QAction):
    def __init__(self,name,iface):
        QAction.__init__(self,self.name(),iface.mainWindow())
        self.iface=iface
        self.canvas=iface.mapCanvas()
        self.setWhatsThis(self.desc())
        self.setToolTip(self.desc())
        self.setCheckable(True)
        QObject.connect(self,SIGNAL("changed()"),self.changedAction)
        return None

    def changedAction(self):
        if self.isChecked():
            QSettings().setValue("/clickfu/set/"+self.name(),True)
        else:
            QSettings().setValue("/clickfu/set/"+self.name(),False)
        

class cfTool(QgsMapTool):
    def __init__(self,iface,clickActions):
        QgsMapTool.__init__(self,iface.mapCanvas())
        self.iface=iface
        self.canvas=iface.mapCanvas()
        self.cursor = QCursor(Qt.WhatsThisCursor)
        self.clickActions = clickActions
        sb = self.iface.mainWindow().statusBar()
        sb.showMessage("click to open web services pages")
        return None
    def canvasReleaseEvent(self,e):
        point = self.canvas.getCoordinateTransform().toMapPoint(e.pos().x(),e.pos().y())

        ### FIXME? Not sure if this is the right way to get coords
        # see Marti Dobias' message on qgis-dev
        # l = self.canvas.currentLayer()
        # if l:
        #    lp = self.toMapCoordinates(e.pos())
        #    print "lp is ",lp
        sb = self.iface.mainWindow().statusBar()
        pt85 = pointToWGS84(point)
        delay = QSettings().value("/clickfu/delay",QVariant(0.0)).toDouble()[0]
        sb.showMessage("Opening "+str(len(self.clickActions))+" web pages")
        for a in self.clickActions:
            if a.isChecked():
                url = a.createURL(pt85.y(),pt85.x())
                QDesktopServices.openUrl(QUrl(url))
                if not a == self.clickActions[-1] and delay > 0:
                    # probably never see this (until I thread/event things)
                    sb.showMessage("Next page in "+str(delay)+" seconds")
                    time.sleep(delay)
        sb.showMessage("All pages opened")
        return None

    def activate(self):
        QgsMapTool.activate(self)
        self.canvas.setCursor(self.cursor)
   


def convertLat(lat):
    """ convert latitude in signed decimal degrees to (degrees, minutes, seconds, hemisphere) """
    return convertDMS(lat,"NS")

def convertLon(lon):
    return convertDMS(lon,"EW")

def convertDMS(dms,hemis):
    if dms > 0:
        hemi=hemis[0]
    else:
        hemi=hemis[1]
        dms=-dms
    d = int(dms)
    ms = (dms-d) * 60.0
    m = int(ms)
    s = (ms - m) * 60.0
    return (d,m,s,hemi)


def pointToWGS84(point):
    p = QgsProject.instance()
    (proj4string,ok) = p.readEntry("SpatialRefSys","ProjectCRSProj4String")
    if not ok:
        return point
    t=QgsCoordinateReferenceSystem()
    t.createFromEpsg(4326)
    f=QgsCoordinateReferenceSystem()
    f.createFromProj4(proj4string)
    transformer = QgsCoordinateTransform(f,t)
    pt = transformer.transform(point)
    return pt
